package com.huluobo.a2205kotlinjetpackdemo.paging

import android.util.Log
import androidx.paging.PagingSource
import androidx.paging.PagingState
import java.lang.Exception

/**
 *  Created by LC on 2024/9/18.
 */
class RepoPagingSource(val apiService: ApiService) : PagingSource<Int, DataItem>() {
    override fun getRefreshKey(state: PagingState<Int, DataItem>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, DataItem> {
        return try {
            val page = params.key ?: 1//当前的页码,如果为空默认等于1,如果不为空,就是当前的页码,比如234
            val pageSize = params.loadSize //当前页面中item的数量
            val repoResponse = apiService.getPagingData(page, pageSize) //发起网络请求,产生reposponse返回
            val repoItems = repoResponse.items//请求返回的数据源,类似于Adapter中的Data
            //以上4步最终目的是拿到请求的数据源

            Log.i("TagA","items:${repoItems.size}")

            val preKey = if (page > 1) page - 1 else null //向前翻页的页码,必须大于1
            val nextKey =
                if (repoItems.isNotEmpty()) page + 1 else null //向后翻页的页码,需要判断返回的数据源不能为空,为空则代表已经没有更多数据了,再向后翻页也没有意义
            LoadResult.Page(repoItems, preKey, nextKey)//相当于success,请求成功,填入数据,与向前向后翻页的页码
        } catch (e: Exception) {
            LoadResult.Error(e)//相当于failed
        }
    }
}